package com.quick.util;

import com.alibaba.fastjson.JSONObject;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import net.coobird.thumbnailator.Thumbnails;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
/**
 * @author lipeng
 * @date 2021/11/4 10:26
 */
public class ImgUtil {
    // 读取图片的全部信息
    public static void readImgAll(File file) throws ImageProcessingException, IOException {
        Metadata metadata = ImageMetadataReader.readMetadata(file);
        System.out.println("---打印全部详情---");
        for (Directory directory : metadata.getDirectories()) {
            for (Tag tag : directory.getTags()) {
                System.out.format("[%s] - %s = %s\n",
                        directory.getName(), tag.getTagName(), tag.getDescription());
            }
            if (directory.hasErrors()) {
                for (String error : directory.getErrors()) {
                    System.err.format("ERROR: %s", error);
                }
            }
        }
    }
    // 读取图片的常用信息,并将信息封装到集合里面
    public static Map<String, String> readImgNormal(File file) throws ImageProcessingException, IOException {
        Metadata metadata = ImageMetadataReader.readMetadata(file);
        Map<String,String> map = new HashMap<>();
        for (Directory directory : metadata.getDirectories()) {
            for (Tag tag : directory.getTags()) {
                String tagName = tag.getTagName();  //标签名
                String desc = tag.getDescription(); //标签信息
                if (tagName.equals("Image Height")) {
                    map.put("imgHeigh" , desc);
                } else if (tagName.equals("Image Width")) {
                    map.put("imgWeith" , desc);
                } else if (tagName.equals("Date/Time Original")) {
                    map.put("time" , desc);
                } else if (tagName.equals("GPS Latitude")) {
                    map.put("lat" , GpsUtil.pointToLatlong(desc));
                } else if (tagName.equals("GPS Longitude")) {
                    map.put("log" , GpsUtil.pointToLatlong(desc));
                }
            }
        }
        return map;
    }
    /**
     * api_key：注册的百度api的key
     * coords：经纬度坐标
     * http://api.map.baidu.com/reverse_geocoding/v3/?ak="+api_key+"&output=json&coordtype=wgs84ll&location="+coords
     * <p>
     * 经纬度转地址信息
     *
     * @param lat  维度
     * @param log 精度
     * @return add 地址
     */
    public static Map<String, String> parseAdd(String log, String lat) throws IOException {
        Map<String,String> adress = new HashMap<>();
        String apiKey = "YNxcSCAphFvuPD4LwcgWXwC3SEZZc7Ra";
        //lat 小  log  大
        //参数解释: 纬度,经度 type 001 (100代表道路，010代表POI，001代表门址，111可以同时显示前三项)
        String urlString = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=" + apiKey + "&output=json&coordtype=wgs84ll&location=" + (lat + "," + log);
        String res = "";
        try {
            URL url = new URL(urlString);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line+"\n";
            }
            in.close();
        } catch (Exception e) {
            System.out.println("error in wapaction,and e is " + e.getMessage());
        }
        JSONObject object = JSONObject.parseObject(res);
        if (object.containsKey("result")) {
            JSONObject result = object.getJSONObject("result");
            if (result.containsKey("addressComponent")) {
                JSONObject addressObj = object.getJSONObject("result").getJSONObject("addressComponent");
                adress.put("country", (String) addressObj.get("country"));
                adress.put("province", (String) addressObj.get("province"));
                adress.put("city", (String) addressObj.get("city"));
                adress.put("district", (String) addressObj.get("district"));
                adress.put("street", (String) addressObj.get("street"));
            }
        }else {
            adress = null;
        }
        return adress;
    }
    // 将图片里面的经纬度通过百度地图的api解析成详细的地址
    public static Map<String, String> parseAddByImg(File file) throws ImageProcessingException, IOException {
        Map<String, String> map = readImgNormal(file);
        String lat = (String) map.get("lat");
        String log = (String) map.get("log");
        return parseAdd(log,lat);
    }
    
    public static HashMap<String, Object> readPicInfo(String file_path) {
    	HashMap<String, Object> map = new HashMap<String,Object>();
    	Tag tag = null;
        File jpegFile = new File(file_path);
        Metadata metadata;
        try {
            metadata = JpegMetadataReader.readMetadata(jpegFile);
            Iterator<Directory> it = metadata.getDirectories().iterator();
            while (it.hasNext()) {
                Directory exif = it.next();
                Iterator<Tag> tags = exif.getTags().iterator();
                while (tags.hasNext()) {
                    tag = (Tag) tags.next();
                    System.out.println(tag.getTagName()+"--"+tag.getDescription());
                }
            }
        } catch (JpegProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    	return map;
    }
    public static String[] readExif(File file) throws ImageProcessingException, IOException {
    	 
        String[] array = new String[3];
//如果你对图片的格式有限制，可以直接使用对应格式的Reader如：JPEGImageReader
        ImageMetadataReader.readMetadata(file)
                .getDirectories().forEach(v ->
                v.getTags().forEach(t -> {
                    System.out.println(t.getTagName() + " ： " + t.getDescription());
                    switch (t.getTagName()) {
                        //                    经度
                        case "GPS Longitude":
                            array[0] = t.getDescription();
                            break;
                        //                        纬度
                        case "GPS Latitude":
                            array[1] = t.getDescription();
                            break;
                        //                        拍摄时间
                        case "Date/Time Original":
                            array[2] = t.getDescription();
                        default:
                            break;
                    }
                })
        );
        return array;
    }
    
    public static void pdfToImages(String imgName) {

    	File file = new File("D:\\sss\\专科.pdf");
    	try {
    		PDDocument doc = new PDDocument();
    		doc.save(file);
    		PDFRenderer renderer = new PDFRenderer(doc);
    		for (int i = 0; i < doc.getNumberOfPages(); i++) {
    			BufferedImage image = renderer.renderImageWithDPI(i, 296);
    			ImageIO.write(image, "PNG", new File("D:\\sss\\pdfbox_image.png"));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
    
    }
    
    public  static void wordToImg() {
    	   try {
               String wordFilePath = "D:\\360MoveData\\Users\\Administrator\\Desktop\\发布日期.doc";
               String outputImagePath = "D:\\sss\\";
	    	XWPFDocument document = new XWPFDocument(new FileInputStream(wordFilePath));
	
	        List<XWPFPictureData> pictures = document.getAllPictures();
	        for (int i = 0; i < pictures.size(); i++) {
	            XWPFPictureData picture = pictures.get(i);
	            byte[] pictureData = picture.getData();
	            BufferedImage image = ImageIO.read(new ByteArrayInputStream(pictureData));
	
	            String imageFileName = outputImagePath + "_" + (i + 1) + ".png";
	            ImageIO.write(image, "png", new FileOutputStream(new File(imageFileName)));
	        }
	
	        document.close();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
    }
    /**
     * 压缩
     * @param imgName
     * @throws IOException
     */
    public static void  reduce(String imgName) throws IOException {
    	 File input = new File(imgName);
    	 BufferedImage  img = ImageIO.read(input);
    	 File outputFile = new File("output.png");
    	 ImageIO.write(img, "png", outputFile);
    	 Thumbnails.of(outputFile)
        .scale(0.5f) // 值在0到1之间,1f就是原图大小,0.5就是原图的一半大小
        .outputQuality(1f) // 值也是在0到1,越接近于1质量越好,越接近于0质量越差
        .toFile("D:\\data\\马文成-本科\\马文成-本科\\身份证反面1.jpg"); // 压缩后文件的路径
    }
    
    public static void main(String[] args) throws IOException {
    	//ImgUtil.print("https://stqifu-test.oss-cn-qingdao.aliyuncs.com/ddc/works/2024-02-09/1707409485791233.png");
    	//ImgUtil.reduce("D:\\data\\马文成-本科\\马文成-本科\\身份证反面.jpg");
    	ImgUtil.pdfToImages("");
	}
}

